const express = require('express')
const app = express()
const router = express.Router()
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const keys = require('../../config/keys.js')
const passport = require('passport')
// 密码加密
const bcrypt = require('bcrypt')
const User = require('../../models/User.js')
// 测试
router.get('/test',(req,res) => {
  res.json('ok')
})
//注册
router.post('/register',(req,res) => {
  console.log(12354)
  User.findOne({email:req.body.email})
  .then((user) => {
    if(user){
      // res.json(user)
    res.status(400).json({email:'邮箱已被注册'})
    }else{
      const avatar = gravatar.url(req.body.email, {
        s:"200",
        r:"pg",
        d:"mm"
      })
      let newUser =new User( {
        name:req.body.name,
        email:req.body.email,
        password:req.body.password,
        avatar,
      })
      bcrypt.genSalt(10,function(err,salt){
        bcrypt.hash(newUser.password,salt, (err,hash) => {
          if(err) throw err

          newUser.password = hash 

          newUser
          .save()
          .then(user => res.json(user))
          .catch(err => {
            console.log(err)
          })
        })
      })
    }
  })
})

// 登陆
router.post('/login',(req,res) => {
  const email = req.body.email
  const pwd = req.body.password
  User.find({email})
  .then(user => {
    console.log(user)
    if(user.length <= 0){
      return res.status(404).json({email:'邮箱不存在'})
    }
      // 密码匹配
      bcrypt.compare(pwd,user[0].password).then(isMatch => {
        if (isMatch) {
          const rule = { id: user[0].id, name: user[0].name, avatar: user[0].avatar };
          // 规则  secrit 过期时间 
          // 获得token
          let secretOrPrivateKey= keys.secretOrPrivateKey
          jwt.sign(rule, secretOrPrivateKey,{ expiresIn: 3600 }, (err, token) => {
            if (err) throw err;
            res.json({
              success: true,
              token: 'Bearer ' + token
            });
          });
        } else {
          return res.status(400).json('密码错误!');
        }
      }).catch(err => {
        console.log(err)
      })
  })
})


// 操作数据的接口 --- 客户端带着token来访问数据
router.get(
  '/current',
  // 这个地方要做token的验证
  passport.authenticate('jwt',{session:false} ),
  (req,res) => {
    res.json({
      id:req.user.id,
      name:req.user.name,
      email:req.user.email,
      avatar:req.user.avatar
    })
  }
)





















module.exports = router